<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>6.代理模式典型应用之节流</title>
</head>
<style>
    #container{
        width: 500px;
        height: 1000px;
        background-color: red;
    }
    #box{
        width: 500px;
        height: 300px;
        border: 1px solid blue;
        overflow: scroll;
    }
</style>
<body>
    <div id="box">
        <div id="container"></div>
    </div>
    
    <script>
        let container = document.getElementById('box');
        let lastTime = Date.now();
        function throttle(fn,interval) { 
            let lastExecuteTime//上次的执行时间
            return function () { 
                let context = this;
                let now = Date.now();
                if(lastExecuteTime){
                    if(now - lastExecuteTime >interval){
                        fn.apply(context,arguments);
                        lastExecuteTime = now;
                        console.log('非首次执行');
                    }
                }else{
                    console.log('首次执行');
                    fn.apply(context,arguments);
                    lastExecuteTime = now;
                }
             }
         }
        function scrollFn() { 
            let nowTime =  Date.now();
            let duringTime =  (nowTime - lastTime)/1000;
            console.log('滚动事件触发啦～间隔是：',duringTime);
            lastTime = nowTime;
         }
        container.addEventListener('scroll',throttle(scrollFn,1000),false)
    </script>
</body>
</html>